<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    style="margin-top: -15px"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      pagination
      background
      border
      height="740"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <!-- 反馈对话框 -->
    <el-dialog
      :title="dialogType === 1 ? '人工分析' : '确认'"
      :visible.sync="show"
      width="500px"
      append-to-body
    >
      <el-table
        v-if="dialogType === 2"
        :data="model.combinationVos"
        style="width: 100%"
        height="390"
      >
        <el-table-column label="选择" width="60" align="center">
          <template slot-scope="scope">
            <el-radio
              :label="scope.$index + 1"
              v-model="radio"
              @change.native="getCurrentRow(scope.row)"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="负载组合" show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <el-form
        v-else
        ref="editForm"
        :model="model"
        :rules="rules"
        label-width="100px"
        class="mt20"
      >
        <el-form-item label="分析意见" prop="opinion">
          <el-input
            type="textarea"
            v-model="model.opinion"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submit">确 定</el-button>
        <el-button size="small" @click="close('form')">取 消</el-button>
      </div>
    </el-dialog>
  </lb-layout>
</template>

<script>
import {
  malignantLoadList,
  malignantLoadConfirm,
  malignantLoadOpinion,
} from "@/api/sub/portrayal";
import { mul } from "@/utils/index";
import CascaderSelect from "@/components/Select/CascaderSelect";
import RemoteSelect from "@/components/Select/RemoteSelect";
export default {
  name: "perniciousLoad",
  dicts: ["warning_instruct_type", "dc_portrait_malignant_load"],
  components: {
    CascaderSelect,
    RemoteSelect,
  },
  data() {
    return {
      dialogType: 1,
      radio: "",
      netwoekChose: null,
      show: false,
      model: {
        id: null,
        opinion: "",
        combinationVos: [],
      },
      dialogType: null,
      rules: {
        opinion: [
          {
            required: true,
            message: "请输入分析意见",
          },
        ],
      },
      apsForm: {
        formRef: "form",
        labelWidth: "100px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            date: {
              label: "创建时间:",
              typeName: "el-date-picker",
              type: "daterange",
              size: "small",
              "value-format": "yyyy-MM-dd",
              "start-placeholder": "开始日期",
              "end-placeholder": "结束日期",
            },
            sysDeptId: {
              label: "用能单位:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let valNum = that.$refs?.form?.getFieldsValue().sysDeptId;
                return (
                  <div>
                    <CascaderSelect
                      value={valNum}
                      values={valNum}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"请选择"}
                      onInput={that.handlerLiandong}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            deviceMonitoringNetworksId: {
              label: "能耗终端:",
              typeName: "el-select",
              render: () => {
                let that = this;
                return (
                  <div>
                    <RemoteSelect
                      v-model={that.netwoekChose}
                      varient="networks"
                      extraParams={that.extraParams}
                      placeholder={"请选择"}
                      size={"small"}
                      onInput={that.choseNetwork}
                    ></RemoteSelect>
                  </div>
                );
              },
            },
            // meterDeviceCode: {
            //   typeName: "el-input",
            //   placeholder: "计量设备",
            // },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            // {
            //   label: "导出",
            //   type: "success",
            //   typeName: "el-button",
            //   size: "small",
            //   icon: "el-icon-upload2",
            //   click: this.handleDerive,
            // },
          ],
        },
      },
      tableData: {
        column: [
          {
            prop: "sysDeptName",
            label: "用能单位",
            showOverflowTooltip: true,
            minWidth: 100,
          },
          {
            prop: "deviceMonitoringNetworksName",
            label: "能耗终端",
            minWidth: 100,
            showOverflowTooltip: true,
          },
          // {
          //   prop: "meterDeviceCode",
          //   label: "计量设备",
          //   minWidth: 100,
          //   showOverflowTooltip: true,
          // },
          {
            prop: "recognitionAccuracy",
            label: "识别精准度",
            width: 120,
            render: (h, params) => {
              let text = params.row.recognitionAccuracy
                ? mul(params.row.recognitionAccuracy, 100) + "%"
                : "";
              return h("div", {}, text);
            },
          },
          {
            prop: "opinion",
            label: "被识别累计能耗",
            showOverflowTooltip: true,
            minWidth: 120,
          },
          {
            prop: "createTime",
            label: "创建时间",
            showOverflowTooltip: true,
            minWidth: 120,
          },
          {
            prop: "status",
            label: "状态",
            width: 120,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.dc_portrait_malignant_load}
                    value={scope.row.status}
                  />
                </div>
              );
            },
          },
          {
            prop: "confirmTime",
            label: "确认时间",
            showOverflowTooltip: true,
            minWidth: 120,
          },
          {
            prop: "opinion",
            label: "人工干预意见",
            showOverflowTooltip: true,
            minWidth: 120,
          },
          {
            label: "操作",
            width: "200",
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              if (scope.row.status === 0) {
                return (
                  <div>
                    {
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-check"
                        onClick={() => {
                          that.handleOpinion(scope.row, 2);
                        }}
                      >
                        确认
                      </el-button>
                    }
                    {
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-close"
                        onClick={() => {
                          that.handleConfirm(scope.row, 2);
                        }}
                      >
                        误报
                      </el-button>
                    }
                    {
                      <el-button
                        v-hasPermi={["energy:neutralNeutral:confirm"]}
                        size="small"
                        type="text"
                        icon="el-icon-document-checked"
                        onClick={() => {
                          that.handleOpinion(scope.row, 1);
                        }}
                      >
                        人工分析
                      </el-button>
                    }
                  </div>
                );
              } else {
                return (
                  <div>
                    {
                      <el-button
                        v-hasPermi={["energy:neutralNeutral:confirm"]}
                        size="small"
                        type="text"
                        icon="el-icon-document-checked"
                        onClick={() => {
                          this.handleOpinion(scope.row, 1);
                        }}
                      >
                        人工分析
                      </el-button>
                    }
                  </div>
                );
              }
            },
          },
        ],
        data: [],
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      templateSelection: null,
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    // tableHeaderCellStyle({ row, column, rowIndex, columnIndex }) {
    //   if (columnIndex === 7) {
    //     return "background:rgba(223,240,216,0.4)";
    //   } else if (columnIndex === 8) {
    //     return "background:rgba(242,222,222,0.4)";
    //   } else if (columnIndex === 9) {
    //     return "background:rgba(217,237,247,0.4)";
    //   }
    // },
    // //设置指定行、列、具体单元格颜色
    // cellStyle({ row, column, rowIndex, columnIndex }) {
    //   //指定坐标rowIndex ：行，columnIndex ：列
    //   if (columnIndex === 7) {
    //     return "background:rgba(223,240,216,0.4)";
    //   } else if (columnIndex === 8) {
    //     return "background:rgba(242,222,222,0.4)";
    //   } else if (columnIndex === 9) {
    //     return "background:rgba(217,237,247,0.4)";
    //   }
    // },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      this.$store.commit("app/updateApiCount", "add");
      await malignantLoadList(query)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!301003");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const { date, ...other } = this.$refs?.form?.getFieldsValue();
      const [startTime, endTime] =
        this.$refs?.form?.getFieldsValue().date || [];
      const data = {
        ...other,
        deviceMonitoringNetworksId: this.netwoekChose,
        endTime,
        startTime,
      };
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val, flag) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val, flag) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    //重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    // 联动
    handlerLiandong(value) {
      this.netwoekChose = null;
      let result;
      if (value && value.length > 0) {
        result = value[value.length - 1];
      } else {
        result = null;
      }
      this.$refs?.form?.setFieldValue("sysDeptId", result);
      // 请求能耗终端
      this.extraParams = {
        sysDeptId: result,
      };
    },
    /* 选择能耗终端 */
    choseNetwork(value) {
      this.netwoekChose = value;
    },
    // 导出
    handleDerive() {},
    /** 人工确认 */
    handleConfirm(row, type) {
      let that = this;
      let text = type === 1 ? "确认要人工确认吗？" : "确认要误报吗？";
      that.$modal
        .confirm(text)
        .then(function () {
          malignantLoadConfirm({ id: row.id, confirmStatus: type })
            .then((res) => {
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }
              that.$modal.msgSuccess("操作成功");
              that.handlerSearchDetail();
            })
            .catch(function () {
              // this.$message.error("系统错误,请联系管理员!301009");
            });
        })
        .catch(() => {});
    },
    close() {
      if (this.dialogType === 1) {
        this.resetForm("editForm");
      } else {
        this.radio = "";
      }
      this.show = false;
    },
    /** 人工分析 */
    handleOpinion(row, flag) {
      this.dialogType = flag;
      this.show = true;
      this.model.id = row.id;
      if (flag === 1) {
        this.model.opinion = row.opinion;
        this.$nextTick(() => {
          this.$refs["editForm"].clearValidate();
        });
      } else {
        this.radio = "";
        this.model.combinationVos = row.combinationVos;
      }
    },
    // 负载组合列表多选
    getCurrentRow(row) {
      // 获取选中数据 row表示选中这一行的数据，可以从里面提取所需要的值
      this.templateSelection = row;
    },
    submit() {
      if (this.dialogType === 1) {
        // 人工分析
        this.remarks();
      } else {
        //确认
        this.confirmLoadCombination();
      }
    },
    remarks() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          const { id, opinion } = this.model;
          malignantLoadOpinion({ id, opinion })
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.close();
              this.handlerSearchDetail();
            })
            .catch((err) => {
              // this.$message.error("系统错误,请联系管理员!301010");
            });
        }
      });
    },
    confirmLoadCombination() {
      if (!this.radio) {
        this.$message.warning("请选择修改的负载组合");
        return false;
      }
      const data = {
        id: this.model.id,
        confirmStatus: 1,
        confirmGroupId: this.templateSelection.groupId,
      };
      malignantLoadConfirm(data)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.close();
          this.handlerSearchDetail();
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!301009");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-radio__label {
  display: none;
}
</style>
